import HTTP_METHOD from './httpMethod'
import { message } from 'antd'

async function errHandler (res) {
  const body = await res.json()
  message.error(body.message)
  return {status: res.status}
}

export const get = async (url) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.GET,
      credentials: 'include',
      headers: new Headers({
        'Accept': 'application/json',
	      'id': 21,
      }),
    })

    const status = res.status
    const body = await res.json()
    if (res.ok) {
      return Object.assign({}, {status}, {body})
    } else {
      message.error(body.message)
      return {status}
    }
  } catch (ex) {
    return {status: ex.status}
  }
}

export const del = async (url) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.DELETE,
      credentials: 'include',
	    headers: new Headers({
		    'id': 1
	    })
    })

    return {status: res.status}
  } catch (ex) {
    return {status: ex.status}
  }
}


export const post = async (url, growthNote) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.POST,
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json;charset=utf-8',
        'Accept': 'application/json',
        'token': window.localStorage.getItem('jwt')
      }),
      body: JSON.stringify(growthNote)
    })

    const status = res.status
    const body = await res.json()
    if (res.ok) {
      return Object.assign({}, {status}, {body})
    } else {
      message.error(body.message)
      return {status}
    }
  } catch (ex) {
    return {status: ex.status}
  }
}

export const update = async (url, growthNote) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.PUT,
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json;charset=utf-8',
        'Accept': 'application/json'
      }),
      body: JSON.stringify(growthNote)
    })

    return {status: res.status}
  } catch (ex) {
    return {status: ex.status}
  }
}
